package com.iqiyi.pps.epg.web.timer;

import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.pps.epg.core.model.channel.ChannelBase;
import com.iqiyi.pps.epg.core.model.channel.ChannelConfig;
import com.iqiyi.pps.epg.core.model.channel.ChannelLog;
import com.iqiyi.pps.epg.core.model.control.ProgramPlatformControl;
import com.iqiyi.pps.epg.core.model.control.ProgramPlatformControlInfo;
import com.iqiyi.pps.epg.core.model.program.ProgramData;
import com.iqiyi.pps.epg.core.service.broadcast.BroadcastControlService;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.service.notifymail.NotifyMailService;
import com.iqiyi.pps.epg.core.service.program.ProgramService;
import com.iqiyi.pps.epg.core.utils.*;
import com.iqiyi.pps.epg.core.utils.mail.MailConstant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Lemuel on 2016/3/2.
 * @desc 节目自动播控下线定时器 (默认执行间隔为15分钟)
 */
public class AutoProgramBroadCastControlTrigger {
    private static Logger logger = LoggerFactory.getLogger(AutoProgramBroadCastControlTrigger.class);

    @Autowired
    private BroadcastControlService broadcastControlService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private ProgramService programService;

    @Autowired
    private NotifyMailService notifyMailService;

    // 节目自动播控下线过期时间， 默认48小时
    /**
     * 定时任务执行入口
     */
    public void task() {
        try {
            autoOffline();
        } catch (Exception e) {
            logger.error("[AutoProgramBroadCastControlTrigger][autoOffline][exception={}]", e);
        }
    }

    /**
     * 设置节目超过时间，自动播控下线.
     */
    private void autoOffline() {
        logger.info("[AutoProgramBroadCastControlTrigger][autoOffLine] start");
        List<ProgramPlatformControlInfo> resultMap = broadcastControlService.fetchProgramPlatControls();
        logger.info("[AutoProgramBroadCastControlTrigger][autoOffline][ready check] " + resultMap.size());

        for (ProgramPlatformControlInfo info : resultMap) {
            boolean result = updateOfflineControls(info);
            if (result) {
                programService.doCheckClearFeedById(info.getProgramId());
            }
        }

    }

    /**
     * 设置相对应的节目平台为播控下线
     *
     * @param info 节目播控相关信息
     * @return true if operating successfully, otherwise false.
     */
    private boolean updateOfflineControls(ProgramPlatformControlInfo info) {
        logger.info("[AutoProgramBroadCastControlTrigger][updateOfflineControls][program_id={}]", info.getProgramId());
        List<ProgramPlatformControl> list = broadcastControlService.getProgramPlatformControls(info.getProgramId());
        Map<Integer, ProgramPlatformControl> controlMap = new HashMap<>();
        List<Integer> platIds = new ArrayList<>();
        for (ProgramPlatformControl control : list) {
            if (control.getAvailableStatus() == ProgramPlatformControl.AVAILABLE_STATUS_ALLOW) {
                control.setAvailableStatus(ProgramPlatformControl.AVAILABLE_STATUS_DENY);
                platIds.add(control.getPlayPlatform());
                controlMap.put(control.getPlayPlatform(), control);
            }
        }
        boolean flag = broadcastControlService.setsWithProgram(info.getProgramId(), controlMap);
        String detail = flag ? "操作成功" : "操作失败";
        String executeResult = "节目ID:[" + info.getProgramId() + "]，节目名称:[" + info.getProgramName() + "]" + detail +
                ";platforms:" + platIds.toString();

        logger.info("[AutoProgramBroadCastControlTrigger][updateOfflineControls][result][{}]", executeResult);
        if (info.getLiveType() == ChannelBase.LIVE_TYPE_LS) {
            writeChannelLog(info.getChannelId(), Constants.LogType.PROGRAM_BROADCAST_OFFLINE.getIndex(), executeResult);
        }

        return flag;
    }

    /**
     * 设置节目聊天室未不启用.
     * @param programId 节目id
     * @return true if operating successfully, otherwise false.
     */
    private boolean updateProgramInfo(long programId) {
        logger.info("[AutoProgramBroadCastControlTrigger][updateProgramInfo][program_id={}]", programId);
        try {
            ProgramData programData = programService.findProgramDataById(programId);
            programData.setChatEnable(0);
            programData.setDaojuEnable(0);
            programData.setSync(0);
            programService.editProgramData(programData);

            // 道具下线通知
            if(StringUtils.isNotBlank(programData.getDaojuId())) {
                int flag = ApiDaojuUtil.linkDaoju(programData.getQipuId(), "epg_system", programData.getDaojuId(),
                        DateTimeUtil.transLongFormat(programData.getStartPlayTime().getTime()),
                        DateTimeUtil.transLongFormat(DateTimeUtil.increaseDate(programData.getStopPlayTime().getTime(), 3)),
                        programData.getChatRoomId() + "",
                        programData.getFreeStatus() == 1 ? ApiDaojuUtil.DAOJU_LIVE_TYPE_FREE : ApiDaojuUtil.DAOJU_LIVE_TYPE_PAID,
                        "2", null);
                if (flag == 0) {
                    doSendDaojuRemind(programData, MailContentUtil.DAOJU_DISABLED_REMIND_TITLE);
                }
                writeChannelLog(programData.getFatherId(), Constants.LogType.DAOJU_LINK.getIndex(),
                        "pid:" + programData.getId() + ":daojuId:" + programData.getDaojuId() + "; flag:" + flag);
            }
        } catch (Exception e) {
            logger.info("[AutoProgramBroadCastControlTrigger][updateProgramInfo][exception={}]", e);
            return false;
        }
        return true;
    }

    /**
     * 通知泡泡接口关闭相应的聊天室
     * @param info 节目播控相关信息
     */
    private void sendOfflineNotice(ProgramPlatformControlInfo info) {
        if (info.isChatEnable() && info.getChatroomId() > 0) {
            logger.info("[AutoProgramBroadCastControlTrigger][updateProgramInfo][program_id={}]", info.getProgramId());
            long flag = ApiChatUtil.deleteChat(info.getChatroomId());
            String result = flag == 0 ? "success" : "failed";
            writeChannelLog(info.getChannelId(), Constants.LogType.CHAT_ROOM_DEL.getIndex(),
                    "[program_id=" + info.getProgramId() + "][room_id=" + info.getChatroomId() + "][result=" + result + "]");
            logger.info("[AutoProgramBroadCastControlTrigger][updateProgramInfo][program_id={}][result={}]",
                    info.getProgramId(), result);
        }
    }

    /**
     * 插入操作日志
     * @param channelId 频道ID
     * @param type 日志类型
     * @param descr 日志描述
     */
    private void writeChannelLog(long channelId, int type, String descr) {
        ChannelLog channelLog = new ChannelLog();
        channelLog.setFatherId(channelId);
        channelLog.setType(type);
        channelLog.setDescr(descr);
        channelLog.setUser(Constants.SYSTEM_USER_SIGN);
        channelService.saveLog(channelLog);
    }

    /**
     * 发送道具提醒邮件
     * @param program 节目数据
     * @param mailTitle 邮件标题类型
     */
    private void doSendDaojuRemind(ProgramData program, String mailTitle) {
        try {
            String[] tos = notifyMailService.getTos( 0, 0 , MailConstant.TOS_TYPE_DAOJU_MAIL_GROUP);
            if( tos.length ==0){
                return ;
            }
            Map<String, String> map = new HashMap<>();
            map.put(MailConstant.P_NAME, program.getPname());
            map.put(MailConstant.P_QIPU_ID, "" + program.getQipuId());
            map.put(MailConstant.P_START_TIME, DateTimeUtil.transLongFormat(program.getStartPlayTime().getTime()));
            map.put(MailConstant.P_STOP_TIME, DateTimeUtil.transLongFormat(program.getStopPlayTime().getTime()));

            String title = String.format(mailTitle, program.getPname());
            String content = MailContentUtil.getContent(MailContentUtil.ContentType.DAOJU_REMIND, map);
            SendMailUtils.send(title, tos, content);
            logger.info("[AutoProgramBroadCastControl][doSendDaojuRemind][title={}][tos = {}]", title, tos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
